package com.yxt.ui;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.yxt.common.sys.CommConstant;
import com.yxt.common.sys.CommUtil;
import com.yxt.common.ui.ActivityStackControlUtil;
import com.yxt.common.ui.StationOverlay;
import com.yxt.exception.InternetException;
import com.yxt.exception.RemoteServerException;
import com.yxt.exception.XmlParserException;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;

public class WaterStationMapActivity extends MapActivity {
	private static final int MODEL_SATELITE = Menu.FIRST+1;
	private static final int MODEL_STREET = Menu.FIRST+2;
	private static final int MODEL_DATALST = Menu.FIRST+3;
	private MapView mapView;
	private List<Map<String,String>> locations = new ArrayList<Map<String,String>>();
	private String watertype;
	private ProgressDialog dialog;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);// 去掉标题栏
		setContentView(R.layout.water_map); // 软件activity的布局
		ActivityStackControlUtil.add(this);
		Button btnBackHome = (Button) findViewById(R.id.btnBackHome);
		btnBackHome.setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
				Intent intent = new Intent();
				intent.setClass(getApplicationContext(), MainActivity.class);
				startActivity(intent);
			}
		});
		mapView = (MapView) findViewById(R.id.map_view);
		initComponent();
	}

	private void initComponent() {
		dialog = new ProgressDialog(this);
		dialog.setTitle("提示");
		dialog.setMessage("数据下载中,请稍候...");
		dialog.show();
		final Handler hanlder = new Handler(){
			// 处理来自线程的消息,并将线程中的数据设置入listview
			public void handleMessage(Message msg)	{
				if (msg.what == 1)	{				
					GeoPoint gpoint = null;
					for(int i = 0; i < locations.size(); i++) {
						Map<String,String> data = locations.get(i);
						StringBuffer title = new StringBuffer();
						title.append(data.get("name")+"("+data.get("code")+")");
						String over = data.get("over");
						if (null != over && !"".equals(over)) {
							title.append("超汛限:" + over + "米");
						}
						title.append("\n");
						title.append("[" + data.get("addr") + "] ");
						title.append("[" + data.get("river") + "]");
						GeoPoint point = new GeoPoint(CommUtil.getGisDegree(data.get("wd")), CommUtil.getGisDegree(data.get("jd")));
						StationOverlay overlay = new StationOverlay(getApplicationContext(),point, title.toString());
						mapView.getOverlays().add(overlay);
						if (i == 0)
							gpoint = point;
					}
					
					MapController mc = mapView.getController();
					mc.setZoom(CommConstant.Config.DEFAULT_ZOOM);
					if (gpoint != null) {
						mc.animateTo(gpoint);
					} else {
						mc.animateTo(new GeoPoint(CommUtil.getGisDegree(CommConstant.Typhoon.DEFAULT_LOCATION[0][0]), CommUtil.getGisDegree(CommConstant.Typhoon.DEFAULT_LOCATION[0][1])));
					}
				}
				dialog.cancel();	
			}
		};
		
		new Thread(){
			public void run(){
				Looper.prepare();
				downloadStation();
				Message m = new Message();
				m.what = 1;
				hanlder.sendMessage(m);	// 给handle发送的消息
				Looper.loop();
			};

		}.start();
	}
	
	private void downloadStation() {
		try {
			InputStream inputStream = getInputStream();
			SAXParserFactory factory = SAXParserFactory.newInstance();
			SAXParser parser = factory.newSAXParser();
			if (null == watertype) {
				parser.parse(inputStream, new WaterDetailHandler());				
			} else {
				parser.parse(inputStream, new WaterStationHandler());
			}
		} catch (IOException e) {
			dialog.cancel();
			throw new InternetException("");
		} catch (ParserConfigurationException e){
			dialog.cancel();
			throw new XmlParserException("");
		} catch(SAXException ex) {
			dialog.cancel();
			throw new XmlParserException("");
		}
	}

	private InputStream getInputStream() throws IOException{
		Intent intent = getIntent();
		watertype = intent.getStringExtra("type");
		String server = CommConstant.Sever.WATER_SERVER;
		InputStream input = null;
		if (CommConstant.DEBUG_MODEL) {
			if (null == watertype) {
				input = new FileInputStream(CommConstant.Config.DEFAULT_PHONE_DIR + CommConstant.Config.XML_LOCATION +"waterdetail.xml");
			} else {
				input = new FileInputStream(CommConstant.Config.DEFAULT_PHONE_DIR + CommConstant.Config.XML_LOCATION +"waterlocation.xml");
			}
		} else {
			String str;
			if (null == watertype) {
				str = server + "water/StaDetail.aspx?iphoneid=" + CommConstant.Main.CURRENT_IPHONE_CODE + "&version=" + CommConstant.Main.CURRENT_IPHONE_VERSION + "&areacode=" + CommConstant.Main.CURRENT_AREA_CODE + "&rvnm="+CommConstant.Main.CURRENT_RIVER_CODE+"&stacode="+intent.getStringExtra("code")+"&type="+CommConstant.Water.WATER_OVER;			
			} else {
				str = server + "water/StaList.aspx?iphoneid=" + CommConstant.Main.CURRENT_IPHONE_CODE + "&version=" + CommConstant.Main.CURRENT_IPHONE_VERSION + "&areacode=" + CommConstant.Main.CURRENT_AREA_CODE + "&rvnm="+CommConstant.Main.CURRENT_RIVER_CODE+"&type="+watertype;
			}
			URL url = new URL(str);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setReadTimeout(CommConstant.Config.DEFAULT_TIMEOUT);
			conn.connect();
			input = conn.getInputStream();
		}
		return input;
	}
		
	private class WaterDetailHandler extends DefaultHandler {	
		private Map<String,String> data = new HashMap<String,String>();
		
		public void startElement(String uri, String localName, String qName,
				Attributes attrs) throws SAXException {
			if ("sta".equals(localName)) {
				for (int i = 0; i < attrs.getLength(); i++) {
					data.put(attrs.getLocalName(i), attrs.getValue(i));
				}
			} else if ("message".equals(localName)) {
				throw new RemoteServerException(attrs.getValue("info"));
			} else {
				String label = attrs.getValue("label");
				if (getString(R.string.locaiton_code).equals(label)) {
					data.put("code", attrs.getValue("value"));
					locations.add(data);
				}
			}
		}
	}
	
	private class WaterStationHandler extends DefaultHandler {
		public void startElement(String uri, String localName, String qName,
				Attributes attrs) throws SAXException {
			if ("station".equals(localName)) {
				Map<String, String> data = new HashMap<String, String>();
				for (int i = 0; i < attrs.getLength(); i++) {
					data.put(attrs.getLocalName(i), attrs.getValue(i));
				}
				locations.add(data);
			} else if ("message".equals(localName)) {
				dialog.cancel();
				throw new RemoteServerException(attrs.getValue("info"));
			}
		}
	}
	
	/**
	 * 创建底部菜单
	 * */
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		menu.add(0, MODEL_SATELITE, 1, R.string.model_satelite);
		menu.add(0, MODEL_STREET, 2, R.string.model_street);
		if (null != watertype) {
			menu.add(0, MODEL_DATALST, 3, R.string.menu_list);
		}
		return super.onCreateOptionsMenu(menu);
	}
	
	/**
	 * 点击底部菜单项时的处理
	 */
	public boolean onOptionsItemSelected(MenuItem item) {	
		switch (item.getItemId()) {
			case MODEL_SATELITE:
				mapView.setSatellite(true);
				mapView.setStreetView(false);
				return true;
			case MODEL_STREET:
				mapView.setStreetView(true);
				mapView.setSatellite(false);		
				return true;
			case MODEL_DATALST:
				Intent intent = new Intent();
				intent.putExtra("type", watertype);
				intent.setClass(getApplicationContext(), WaterStationListActivity.class);
				startActivity(intent);
				return true;
		}
		return super.onOptionsItemSelected(item);
	}
	
	protected boolean isRouteDisplayed() {
		return false;
	}

	protected void onDestroy() {
		super.onDestroy();
        ActivityStackControlUtil.remove(this);
	}
}